<template>
  <div id="article">
    <!-- {{ pageParam }} -->
    <div>
      <el-button
        size="small"
        type="primary"
        icon="el-icon-s-promotion"
        @click="toAdd"
        plain
        round
        >新增</el-button
      >
      <el-button
        size="small"
        type="primary"
        icon="el-icon-download"
        @click="export2Excel"
        plain
        round
        >数据导出</el-button
      >
      <div class="input">
        <div class="widthDiv marginLeft">
          <el-input
            size="small"
            clearable
            v-model="pageParam.title"
            maxlength
            placeholder="请输入内容"
          ></el-input>
        </div>
        <div class="widthDiv">
          <el-select
            size="small"
            clearable
            v-model="pageParam.categoryId"
            placeholder="请选择分类"
          >
            <el-option
              v-for="item in categoryData"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </div>
        <el-button
          size="small"
          type="primary"
          icon="el-icon-search"
          @click="toSearch"
          >搜索</el-button
        >
      </div>
    </div>
    <el-table
      border
      size="small"
      :data="tableData"
      style="width: 100%"
      max-height="500"
    >
      <el-table-column fixed align="center" label="编号" width="200">
        <!-- scope  插槽作用域对象 -->
        <template slot-scope="scope">
          <i class="el-icon-time"></i>
          <span style="margin-left: 10px">{{ scope.row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="发布时间" width="300">
        <template slot-scope="scope">
          <i class="el-icon-time"></i>
          <span style="margin-left: 10px">{{
            moment(scope.row.publishTime).format("YYYY-MM-DD HH:mm:ss")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="标题" width="400">
        <template slot-scope="scope">
          <el-tag type="success" size="medium">{{ scope.row.title }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="status" label="状态" width="200"
        ><template slot-scope="scope">
          <el-tag
            v-if="scope.row.status == '未审核'"
            type="info"
            size="medium"
            >{{ scope.row.status }}</el-tag
          >
          <el-tag
            v-else-if="scope.row.status == '审核通过'"
            type="success"
            size="medium"
            >{{ scope.row.status }}</el-tag
          >
          <el-tag
            v-else-if="scope.row.status == '推荐'"
            type="primary"
            size="medium"
            >{{ scope.row.status }}</el-tag
          >
          <el-tag v-else type="danger" size="medium">{{
            scope.row.status
          }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" prop="category.name" label="所属分类">
      </el-table-column>
      <el-table-column fixed="right" align="center" label="操作" width="200">
        <template slot-scope="scope">
          <el-button
            id="edit"
            icon="el-icon-edit"
            type="info"
            circle
            @click="handleEdit(scope.row)"
          ></el-button>
          <el-button
            id="delete"
            type="warning"
            circle
            icon="el-icon-delete"
            @click="handleDelete(scope.row.id)"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="block">
      <span class="demonstration"></span>
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageParam.page"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="pageParam.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
    <el-dialog
      width="70%"
      :title="title"
      :visible.sync="visible"
      :before-close="beforeClose"
    >
      <el-form :model="form" ref="ruleForm" :rules="rules">
        <el-form-item prop="title" label="标题" :label-width="formLabelWidth">
          <el-input v-model="form.title" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item
          prop="categoryId"
          label="所属分类"
          :label-width="formLabelWidth"
        >
          <el-select
            size="small"
            clearable
            v-model="form.categoryId"
            placeholder="请选择分类"
          >
            <el-option
              v-for="item in categoryData"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item prop="content" label="资讯" :label-width="formLabelWidth">
          <tinymce ref="text" v-model="form.content"> </tinymce>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="toCancel">取 消</el-button>
        <el-button type="primary" @click="toSave('ruleForm')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from "../../utils/request";
// 引入tinymce
import Tinymce from "../../components/Tinymce/index";
let moment = require("moment");
export default {
  // 注册组件
  components: {
    // 组件名（标签名）：组件对象
    tinymce: Tinymce,
  },
  data() {
    return {
      formLabelWidth: "100px",
      // 表单校验规则
      rules: {
        title: [{ required: true, message: "请输入资讯标题", trigger: "blur" }],
        categoryId: [
          { required: true, message: "请选择资讯分类", trigger: "change" },
        ],
        content: [
          { required: true, message: "请输入资讯内容", trigger: "blur" },
        ],
      },
      form: {},
      title: "录入资讯信息",
      visible: false,

      total: 0,
      tableData: [],
      // dataOut: [],
      dataExcel: [
        // {outTime:''}
      ],
      // 分页查询的参数
      pageParam: {
        page: 1,
        pageSize: 10,
        title: "",
        categoryId: "",
      },
      categoryData: [],
    };
  },
  computed: {},
  methods: {
    moment,
    // 导出Excel表格
    export2Excel() {
      require.ensure([], () => {
        const { export_json_to_excel } = require("../../excel/Export2Excel");
        const tHeader = ["编号", "发布时间", "标题", "状态"]; // 上面设置Excel的表格第一行的标题
        const filterVal = ["id", "publishTime", "title", "status"];
        const list = this.dataExcel; //把data里的tableData存到list
        console.log(list, "------");
        list.forEach((item) => {
          item.publishTime = moment(item.publishTime).format(
            "YYYY-MM-DD HH:mm:ss"
          );
        });
        const data = this.formatJson(filterVal, list);
        export_json_to_excel(tHeader, data, "列表excel");
      });
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map((v) => filterVal.map((j) => v[j]));
    },
    // 编辑
    handleEdit(row) {
      this.title = "编辑资讯信息";
      this.form = { ...row };
      this.visible = true;
      // this.$refs.text.setContent()
    },

    toSave(formName) {
      this.$refs[formName].validate((valid) => {
        // 校验通过
        if (valid) {
          // console.log(this.form, "=====");
          axios.post("/article/saveOrUpdate", this.form).then((res) => {
            if (res.status == 200) {
              // 保存成功，关闭模态框，刷新数据
              this.$notify({
                title: "成功",
                message: "保存成功",
                type: "success",
              });
              this.toCancel();
              this.pageQuery();
            } else {
              this.$notify.error({
                title: "失败",
                message: res.statusText,
              });
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    toCancel() {
      this.$refs["ruleForm"].resetFields();
      this.visible = false;
    },
    beforeClose(done) {
      this.$refs["ruleForm"].resetFields();
      done();
    },
    // 添加
    toAdd() {
      this.form = {};
      this.visible = true;
      this.title = "录入分类信息";
      setTimeout(() => {
        this.$refs.text.setContent("");
      }, 1000);
      // this.$nextTick(() => {this.$refs.text.setContent('');})
    },
    //   搜索
    toSearch() {
      this.pageParam.page = 1;
      this.pageQuery();
    },
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.pageParam.pageSize = val;
      this.pageQuery();
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.pageParam.page = val;
      this.pageQuery();
    },
    // 分页查找
    async pageQuery() {
      let res = await axios.get("/article/pageQuery", {
        params: this.pageParam,
      });
      this.tableData = res.data.list;
      this.total = res.data.total;
    },

    // 查找分类
    async findAllCategory() {
      let res = await axios.get("/category/findAll");
      this.categoryData = res.data;
    },
    async findAllArticle() {
      let res = await axios.get("/article/findAll");
      this.dataExcel = res.data;
    },

    // 删除
    handleDelete(id) {
      // id就是要删除的分类的对象的id
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        // 如果一个函数有await，那这个函数就是异步函数，要用async修饰一下
        .then(async () => {
          // await等待后面异步函数运行完毕，拿到响应的数据，然后返回
          let res;
          if (id) {
            res = await axios.get("/article/deleteById", { params: { id } });
          }
          this.$notify({
            title: res.status == 200 ? "成功" : "失败",
            message: res.statusText,
            type: res.status == 200 ? "success" : "error",
          });
          // 删除后刷新数据
          this.pageQuery();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
  },
  created() {
    this.pageQuery();
    this.findAllCategory();
    this.findAllArticle();
  },
};
</script>
<style scoped>
.widthDiv {
  width: 200px;
  display: inline-block;
  margin-right: 10px;
  margin-bottom: 10px;
}
.marginLeft {
  margin-left: 10px;
}
.input {
  float: right;
}
</style>